<template>
  <el-form ref="form" :label-position="device === 'mobile' ? 'top' : 'right'" label-width="100px" :model="form" :rules="rules">
    <el-form-item label="名称" prop="name">
      <el-input v-model.trim="form.name" autocomplete="off" placeholder="请输入名称" />
    </el-form-item>
    <el-form-item label="Key" prop="key">
      <el-input v-model.trim="form.key" autocomplete="off" placeholder="请输入Key" />
    </el-form-item>
    <el-form-item label="SubKey" prop="subKey">
      <el-input v-model.trim="form.subKey" autocomplete="off" placeholder="请输入SubKey" />
    </el-form-item>
    <el-form-item label="值" prop="value">
      <el-input v-model.trim="form.value" autocomplete="off" placeholder="请输入值" />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model.trim="form.remark" autocomplete="off" placeholder="请输入备注" :rows="2" type="textarea" />
    </el-form-item>
    <el-form-item v-if="device === 'mobile'" class="submit-content">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </el-form-item>
  </el-form>
</template>
  
<script>
import { mapGetters } from 'vuex'
import { API_dictCreate, API_dictEdit } from '@/api/dict'
export default {
  name: 'FormEdit',
  props: {
    formData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      form: {
        name: '',
        key: '',
        subKey: '',
        value: '',
        remark: '',
      },
      rules: {
        name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
        key: [{ required: true, trigger: 'blur', message: '请输入Key' }],
        subKey: [{ required: true, trigger: 'blur', message: '请输入SubKey' }],
        value: [{ required: true, trigger: 'blur', message: '请输入值' }],
      },
    }
  },
  computed: {
    ...mapGetters({
      device: 'settings/device',
    }),
  },
  watch: {
    'formData': {
      handler(newData) {
        if (newData) {
          this.form = Object.assign({}, this.formData)
        }
      },
      immediate: true,
    },
  },
  methods: {
    close() {
      this.$refs['form'].resetFields()
      this.form = this.$options.data().form
      if (this.device === 'mobile') {
        this.$router.push({
          name: 'Dict',
          params: { refresh: true },
        })
      }
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (this.form.code) {
            const { message } = await API_dictEdit(this.form)
            this.$baseMessage(message, 'success')
          } else {
            const { message } = await API_dictCreate(this.form)
            this.$baseMessage(message, 'success')
          }
          this.$emit('fetch-data')
          this.close()
        } else {
          return false
        }
      })
    },
  },
}
</script>
  